﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Text.RegularExpressions;

namespace Wars2Wgs
{
    public partial class Form1 : Form
    {
        double[] TableX = new double[660 * 450];
        double[] TableY = new double[660 * 450];
        bool InitTable = false;
        double[,] pointCoords;
        public Form1()
        {
            InitializeComponent();

            LoadText();
        }

        private int GetID(int I, int J)
        {
            return I + 660 * J;
        }

        private void LoadText()
        {
            using (StreamReader sr = new StreamReader("Mars2Wgs.txt"))
            {
                string s = sr.ReadToEnd();

                //textBox1.Text = s;

                string[] lines = s.Split('\n');

                //MessageBox.Show(lines.Length.ToString());

                Match MP = Regex.Match(s, "(\\d+)");

                int i = 0;
                while (MP.Success)
                {
                    //MessageBox.Show(MP.Value);
                    if (i % 2 == 0)
                    {
                        TableX[i / 2] = Convert.ToDouble(MP.Value) / 100000.0;
                    }
                    else
                    {
                        TableY[(i - 1) / 2] = Convert.ToDouble(MP.Value) / 100000.0;
                    }
                    i++;
                    MP = MP.NextMatch();
                }
                InitTable = true;
                //MessageBox.Show((i / 2).ToString());
            }
        }

        /// <summary>
        /// x是117左右，y是31左右
        /// </summary>
        /// <param name="xMars"></param>
        /// <param name="yMars"></param>
        /// <param name="xWgs"></param>
        /// <param name="yWgs"></param>
        private void Parse(double xMars, double yMars, ref double xWgs, ref double yWgs)
        {
            int i, j, k;
            double x1, y1, x2, y2, x3, y3, x4, y4, xtry, ytry, dx, dy;
            double t, u;

            if (!InitTable)
                return;

            xtry = xMars;
            ytry = yMars;

            for (k = 0; k < 10; ++k)
            {
                // 只对中国国境内数据转换
                if (xtry < 72 || xtry > 137.9 || ytry < 10 || ytry > 54.9)
                {
                    return;
                }

                i = (int)((xtry - 72.0) * 10.0);
                j = (int)((ytry - 10.0) * 10.0);

                x1 = TableX[GetID(i, j)];
                y1 = TableY[GetID(i, j)];
                x2 = TableX[GetID(i + 1, j)];
                y2 = TableY[GetID(i + 1, j)];
                x3 = TableX[GetID(i + 1, j + 1)];
                y3 = TableY[GetID(i + 1, j + 1)];
                x4 = TableX[GetID(i, j + 1)];
                y4 = TableY[GetID(i, j + 1)];

                t = (xtry - 72.0 - 0.1 * i) * 10.0;
                u = (ytry - 10.0 - 0.1 * j) * 10.0;

                dx = (1.0 - t) * (1.0 - u) * x1 + t * (1.0 - u) * x2 + t * u * x3 + (1.0 - t) * u * x4 - xtry;
                dy = (1.0 - t) * (1.0 - u) * y1 + t * (1.0 - u) * y2 + t * u * y3 + (1.0 - t) * u * y4 - ytry;

                xtry = (xtry + xMars - dx) / 2.0;
                ytry = (ytry + yMars - dy) / 2.0;
            }

            xWgs = xtry;
            yWgs = ytry;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            double x = Convert.ToDouble(txbX.Text);
            double y = Convert.ToDouble(txbY.Text);

            double xWgs = x;
            double yWgs = y;

            Parse(x, y, ref xWgs, ref yWgs);

            txtResult.Text = "X:" + xWgs.ToString() + ",Y:" + yWgs.ToString();
            txtPoints.Text += xWgs.ToString() + "," + yWgs.ToString();
        }

        private void txtSourceFile_MouseClick(object sender, MouseEventArgs e)
        {
            string filePath = OpenTextFileDialog();
            if (CheckFile(filePath))
            {
                txtSourceFile.Text = filePath;
                txtSaveFile.Text = filePath.Substring(0, filePath.LastIndexOf(".txt")) + "_偏移后.txt";
            }
        }

        private string OpenTextFileDialog()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "文本文件(*.txt)|*.txt";
            fileDialog.Title = "打开文件";
            fileDialog.Multiselect = false;
            if (DialogResult.OK == fileDialog.ShowDialog())
            {
                return fileDialog.FileName;
            }
            return null;
        }

        private bool CheckFile(string filePath)
        {
            if (filePath == null)
                return false;
            return File.Exists(filePath);
        }


        private List<string> GetPointsFromFile(string filePath)
        {
            List<string> coords = new List<string>();
            StreamReader pointsSR = File.OpenText(filePath);
            string coordStr = null;
            while ((coordStr = pointsSR.ReadLine()) != null)
            {
                coords.Add(coordStr);
            }
            try
            {
                pointsSR.Close();
            }
            catch
            {
            }
            return coords;
        }

        private void txtSaveFile_Click(object sender, EventArgs e)
        {
            string filePath = SaveTextFileDialog();

            txtSaveFile.Text = filePath;

        }

        private string SaveTextFileDialog()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.CheckPathExists = true;
            sfd.DefaultExt = "*.txt";
            sfd.Filter = "文本文件(*.txt)|*.txt";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                return sfd.FileName;
            }
            else
                return null;
        }

        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            if (!CheckDirectory(txtSaveFile.Text))
            {
                MessageBox.Show("请选择保存坐标文件的位置");
            }
            StreamWriter sw = new StreamWriter(txtSaveFile.Text);
            for (int coordIndex = 0; coordIndex < pointCoords.Length / 2; coordIndex++)
            {
                sw.WriteLine(pointCoords[coordIndex, 0] + "," + pointCoords[coordIndex, 1]);
            }
            sw.Flush();
            sw.Close();

        }

        private bool CheckDirectory(string p)
        {
            int index = p.LastIndexOf("\\");
            if (index < -1)
                return false;
            else
            {
                if (Directory.Exists(p.Substring(0, index + 1)))
                    return true;
                else
                    return false;
            }
        }

        private void btnTrans_Click(object sender, EventArgs e)
        {
            if (!CheckFile(txtSourceFile.Text))
            {
                MessageBox.Show("请选择一个坐标文件");
            }
            List<string> coords = (GetPointsFromFile(txtSourceFile.Text));
            if (coords == null || coords.Count <= 0)
            {
                return;
            }
            pointCoords = new double[coords.Count, 2];
            int coordIndex = -1;
            foreach (string coordStr in coords)
            {
                coordIndex++;
                string[] coord = coordStr.Split(',');

                double x = Convert.ToDouble(coord[0]);
                double y = Convert.ToDouble(coord[1]);

                double xWgs = x;
                double yWgs = y;

                Parse(x, y, ref xWgs, ref yWgs);
                pointCoords[coordIndex, 0] = xWgs;
                pointCoords[coordIndex, 1] = yWgs;
                txtPoints.Text += xWgs.ToString() + "," + yWgs.ToString() + "\r\n";
            }
        }
    }
}
